package edu.scau.mis.controller.user;

import edu.scau.mis.core.controller.ResultEntity;
import edu.scau.mis.core.redis.RedisCache;
import edu.scau.mis.rest.entity.RestOrder;
import edu.scau.mis.rest.entity.vo.RestOrderVo;
import edu.scau.mis.rest.service.RestOrderItemService;
import edu.scau.mis.rest.service.RestOrderService;
import edu.scau.mis.rest.service.RestSeatService;
import edu.scau.mis.rest.service.RestUserService;
import edu.scau.mis.sys.utils.HttpServletRequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
public class OrderController {

    @Autowired
    RestOrderService restOrderService;

    @Autowired
    RestOrderItemService restOrderItemService;

    @Autowired
    RestUserService restUserService;

    @Autowired
    RestSeatService restSeatService;

    @Autowired
    HttpServletRequest httpServletRequest;

    @Autowired
    RedisCache redisCache;

    @PostMapping("/commitOrder")
    public ResultEntity commitOrder(){
        //获取请求头token
        String openid = HttpServletRequestUtils.getOpenid(httpServletRequest);

        //判断餐位是否可用
        if(!restSeatService.isSeatCanUse(openid)){
            return ResultEntity.error(409, "餐位正在使用中，请重新选择");
        }

        restOrderService.insertOrder(openid);
        restOrderItemService.insertBatch(openid);

        restSeatService.updateSeatStatus(redisCache.getListByIndex(openid, 1).toString(), 1);
        return ResultEntity.success("操作成功");

    }

    @GetMapping("/getNowOrder")
    public ResultEntity getNowOrder(){
        //获取请求头token
        String openid = HttpServletRequestUtils.getOpenid(httpServletRequest);

        RestOrderVo restOrderVo = restOrderService.getNowOrder(openid);
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("allOrder", restOrderVo);

        //清空缓存
        restOrderService.clearCache(openid);

        return ResultEntity.error("操作成功", responseData);
    }

    @GetMapping("getMyOrder")
    public ResultEntity getMyOrder(){
        //获取请求头token
        String openid = HttpServletRequestUtils.getOpenid(httpServletRequest);

        List<RestOrderVo> restOrderVoList = restOrderService.getMyOrder(openid);
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("allOrder", restOrderVoList);

        return ResultEntity.error("操作成功", responseData);
    }



}
